package com.lsp.rabbitmqprovider.controller;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;

@RestController
public class SendAckMessageController implements RabbitTemplate.ReturnCallback, RabbitTemplate.ConfirmCallback {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @GetMapping("/sendAckMessage")
    public void HelloSender(){
        String context = "你好现在是 " + LocalDateTime.now();
        System.out.println("HelloSender发送内容 : " + context);
        //消息消费者确认收到消息后，手动ack回执
        rabbitTemplate.setReturnCallback(this);
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.convertAndSend("TestAckExchange","TestAckRouting", context);
    }

    /**
     * 表示消息发送到交换机但是没有找到队列
     */
    @Override
    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
        System.out.println("---- returnedMessage ----replyCode="+replyCode+" replyText="+replyText+" ");
    }

    /**
     * 成功发送到交换机会触发该回调
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        System.out.println("---- confirm ----ack="+ack+"  cause="+String.valueOf(cause));
        System.out.println("correlationData -->"+correlationData);
        if(ack){
            System.out.println("---- confirm ----ack==true  cause="+cause);
        }else{
            System.out.println("---- confirm ----ack==false  cause="+cause);
        }
    }
}
